package danran.dbapi.service;

import danran.dbapi.common.ResponseDto;
import danran.dbapi.domain.DataSource;
import danran.dbapi.mapper.ApiConfigMapper;
import danran.dbapi.mapper.DataSourceMapper;
import danran.dbapi.utils.PoolUtil;
import danran.dbapi.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
 * @Classname DataSourceService
 * @Description TODO
 * @Date 2022/1/13 15:56
 * @Created by RanCoder
 */
@Service
public class DataSourceService {
    @Autowired
    private DataSourceMapper dataSourceMapper;
    @Autowired
    private ApiConfigMapper apiConfigMapper;

    @Transactional
    public void add(DataSource dataSource) {
        dataSource.setId(UUID.randomUUID().toString());
        dataSource.setCreateTime(TimeUtil.now());
        dataSource.setUpdateTime(TimeUtil.now());
        dataSourceMapper.insert(dataSource);
    }

//    @CacheEvict(value = "datasource", key = "#dataSource.id")
    @Transactional
    public void update(DataSource dataSource) {
        dataSource.setUpdateTime(TimeUtil.now());
        dataSourceMapper.updateById(dataSource);
    }

//    @CacheEvict(value = "datasource", key = "#id")
    @Transactional
    public ResponseDto delete(String id) {
        // 统计有几个api使用了该数据源
        int using = apiConfigMapper.countByDatasoure(id);
        if (using == 0) { // no api is using this datasource
            dataSourceMapper.deleteById(id);
            // 删除该数据源对应的数据库连接池
            PoolUtil.removeJdbcConnectionPool(id);
            return ResponseDto.successWithMsg("删除数据源成功");
        } else {
            return ResponseDto.fail("当前数据源仍有API使用，删除失败!");
        }
    }

//    @Cacheable(value = "datasource", key = "#id", unless = "#result == null")
    public DataSource detail(String id) {
        return dataSourceMapper.selectById(id);
    }

    public List<DataSource> getAll() {
        return dataSourceMapper.selectList(null);
    }

    public String getDBType(Integer id) {
        return dataSourceMapper.selectById(id).getType();
    }

    public List<DataSource> selectBatch(List<String> ids) {
        return dataSourceMapper.selectBatchIds(ids);
    }

    @Transactional
    public void insertBatch(List<DataSource> dataSources) {
        dataSources.forEach(d -> {
            d.setUpdateTime(TimeUtil.now());
            dataSourceMapper.insert(d);
        });
    }

    public DataSource getDataSourceById(String id) {
        return dataSourceMapper.selectById(id);
    }
}
